package zl.controller;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import zl.bean.Category;
import zl.bean.RespBean;
import zl.service.CategoryService;

import javax.validation.constraints.NotNull;
import java.sql.SQLException;

@Controller
@RequestMapping("/api/category")
public class CategoryController  {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/page")
    @ResponseBody
    public RespBean selectAllCategory(@Validated @NotNull(message = "当前页面不能为空") Integer currentPage, String keyword) throws SQLException {
        PageInfo<Category> page = categoryService.selectByPage(currentPage, keyword);
        return RespBean.ok("查询成功",page);
    }

    @PostMapping("/add")
    @ResponseBody
    public RespBean addCategory(@Validated @RequestBody  Category category){
        if(category.getParent_id()==0){
            category.setRank(1);
        }else {
            category.setRank(2);
        }
        int i = categoryService.addCategory(category);
        if(i==1){
            return RespBean.ok("添加成功");
        }else if(i==3){
            return RespBean.error("类名重复，请重新填写");
        }else {
            return RespBean.error("添加失败");
        }
    }

    @GetMapping("/{id}")
    @ResponseBody
    public RespBean selectById(@PathVariable @Validated @NotNull(message = "类别id不能为空") Integer id){
        Category category = categoryService.selectById(id);
        return RespBean.ok("查询成功",category);
    }

    @PostMapping("/update")
    @ResponseBody
    public RespBean updateCategory(@Validated  @RequestBody  Category category){
        if(category.getParent_id()==0){
            category.setRank(1);
        }else {
            category.setRank(2);
        }
        if(StrUtil.hasBlank(category.getName())){
            return RespBean.error("类名不能为空");
        }
        int i = categoryService.updateCategory(category);
        if(i==1){
            return RespBean.ok("修改成功");
        }else{
            return RespBean.error("修改失败");
        }
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    public RespBean deleteCategory(@PathVariable @Validated @NotNull(message = "类别id不能为空") Integer id){
        int i = 3;
        try {
            i = categoryService.deleteCategory(id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if(i==1){
            return RespBean.ok("删除成功");
        }else{
            return RespBean.error("删除失败,该类别有子类或有该类别小说");
        }
    }


}
